package com.android.bookgarden.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.bookgarden.MainActivity;
import com.android.bookgarden.MyApplication;
import com.android.bookgarden.R;
import com.android.bookgarden.apis.Apis;
import com.android.bookgarden.base.BaseActivity;
import com.android.bookgarden.bean.DataBean;
import com.android.bookgarden.bean.HomeAdvBean;
import com.android.bookgarden.bean.UserInfo;
import com.android.bookgarden.constract.RealtConstract;
import com.android.bookgarden.network.HttpType;
import com.android.bookgarden.persenter.BasePersenter;
import com.android.bookgarden.utli.JsonUitl;
import com.android.bookgarden.utli.SpUtils;
import com.android.bookgarden.utli.Utlis;
import com.android.bookgarden.views.LoadingDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by zouqh on 2018/3/18.
 */

public class StartActivity extends BaseActivity implements RealtConstract.View {

    @BindView(R.id.startImage)
    ImageView startImage;
    @BindView(R.id.time)
    TextView time;

    private int timeNum = 6;
    private boolean flag;
    private RealtConstract.Presenter presenter;
    ArrayList<HomeAdvBean> advList;
    private String token ;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_start;
    }

    @Override
    protected void initView() {
        this.setStates("#ffffff");
        presenter = new BasePersenter(this,this);
        presenter.loadData("", "",Apis.GET_HOME_ADV+"1",1002);
//        presenter.loadData("","", Apis.GET_TOKEN,1001);
        token = SpUtils.getInstance().getString(this,"token","");
        if (!TextUtils.isEmpty(token)){
            presenter.loadDataHeader(null,"", Apis.GET_USERINFO,1003, Utlis.getHeadler(this), HttpType.GET);

        }
        checkSelfPermissions("1",new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE});

    }

    private void temb(){
        time.setVisibility(View.VISIBLE);
        mHandler.obtainMessage(1).sendToTarget();
        time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(StartActivity.this, MainActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("adv", (Serializable) advList);
                intent.putExtras(bundle);
                startActivity(intent);
                mHandler = null;
                flag = true;
                finish();
            }
        });
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String str = (String) msg.obj;
            switch (msg.what) {
                case 1:
                    timeNum--;
                    time.setText("跳过" + timeNum + "s");

                    if (timeNum <= 0) {
                        if (!flag) {
                            Intent intent = new Intent(StartActivity.this, MainActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("adv", (Serializable) advList);
                            intent.putExtras(bundle);
                            startActivity(intent);
                            finish();
                        }

                    } else {
                        if (null != mHandler) {
                            stsm();
                        }

                    }
                    break;

                case 2:
//                    Glide.with(StartActivity.this)
//                            .load(beanList.get(0).getNormbody())
//                            .centerCrop()
//                            .dontAnimate()
//                            .into(imageView);
                    break;

                case 1001:

                    if (TextUtils.isEmpty(str)){
                        return;
                    }
                    try {
                        JSONObject object = new JSONObject(str);
                        int code = object.getInt("code");
                        if (code==200){
                            String token = object.getString("data");
                            SpUtils.getInstance().save(StartActivity.this,"token",""+token);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;

                case 1002:
                    try {
                        getHomeAdv((String) msg.obj);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;

                case 1003:
                    LoadingDialog.hideProgress();
                    if (TextUtils.isEmpty(str)){
                        return;
                    }

                    DataBean bean = Utlis.getDataBean(str);
                    if (bean.getCode()==200){
                        MyApplication.getInstance().userInfo = (UserInfo) JsonUitl.stringToObject(bean.getData(), UserInfo.class);
                        SpUtils.getInstance().save(StartActivity.this,"userinfo",""+bean.getData());

                    }else{
//                        showToast(bean.getMessage());
                    }
                    break;
            }

        }
    };

    private void stsm() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = mHandler.obtainMessage(1);
                mHandler.sendMessageDelayed(message, 1000); // send message
            }
        }).start();

    }

    @Override
    public void onRequestPermissions(String str, boolean z) {

        if (z){
            temb();
        }
    }

    @Override
    public void returnData(String data, int urlCode) {
        if (TextUtils.isEmpty(data)){
            return;
        }
        mHandler.obtainMessage(urlCode,data).sendToTarget();
    }

    @Override
    public void LoadError(String errorMsg, int urlCode) {

    }


    private void getHomeAdv(String json) throws JSONException {
        JSONObject object = new JSONObject(json);
        int code = object.getInt("code");
        if (code==200){
           advList = (ArrayList<HomeAdvBean>) JsonUitl.stringToList(object.getString("data"),HomeAdvBean.class);

        }
    }
}
